package com.yanfan.zutai.util;

import com.alibaba.fastjson2.JSON;
import com.yanfan.zutai.domain.vo.BVideoToken;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpPostAndGetUtil {

    private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    public static String doPost(String url, String jsonStr, String username, String password) {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 创建http请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            StringEntity entity = new StringEntity(jsonStr, "text/plain", "UTF-8");
            httpPost.setEntity(entity);
            if (Detect.notEmpty(username) && Detect.notEmpty(password)) {
                httpPost.addHeader("Authorization", "Basic " + Base64
                        .getUrlEncoder()
                        .encodeToString((username + ":" + password).getBytes()));
            }
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(), "utf-8");
            // System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }

    /*
    * List<NameValuePair> params = new ArrayList<NameValuePair>();
    * params.add(new BasicNameValuePair("road_name", ""));
      String res = HttpPostAndGetUtil.doGet(url, params);
     JSONObject jsonObject = JSONObject.parseObject(res);
    * */
    public static String doGet(String url, List<NameValuePair> params, String username, String password) {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";

        try {
            // 创建http请求
            URIBuilder builder = new URIBuilder(url);
            builder.setParameters(params);
            HttpGet httpGet = new HttpGet(builder.build());
            if (Detect.notEmpty(username) && Detect.notEmpty(password)) {
                httpGet.addHeader("Authorization", "Basic " + Base64
                        .getUrlEncoder()
                        .encodeToString((username + ":" + password).getBytes()));
            }
            response = httpClient.execute(httpGet);
            result = EntityUtils.toString(response.getEntity(), "utf-8");
            // System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }

    public static String doPost(String url, List<NameValuePair> params) {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try {
            URIBuilder builder = new URIBuilder(url);
            builder.setParameters(params);
            // 创建http请求
            HttpPost httpPost = new HttpPost(builder.build());
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }

    // 获取emqx在线信息
//    public  static BDeviceResult getDeviceStatus(String url, String username, String password){
//        //创建httpClient对象
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        CloseableHttpResponse response = null;
//        String result = "";
//        BDeviceResult ajaxResult=null;
//        try{
//            //创建http请求
//            URIBuilder builder = new URIBuilder(url);
//            //builder.setParameters(params);
//            HttpGet httpGet = new HttpGet(builder.build());
//            if(Detect.notEmpty(username)&&Detect.notEmpty(password)){
//                httpGet.addHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
//            }
//            response = httpClient.execute(httpGet);
//            result = EntityUtils.toString(response.getEntity(),"utf-8");
//            ajaxResult= JSON.parseObject(result,BDeviceResult.class);
//            //System.out.println(result);
//        }catch (Exception e){
//            e.printStackTrace();
//        }finally {
//            //关闭资源
//            if(response != null){
//                try {
//                    response.close();
//                }catch (IOException ioe){
//                    ioe.printStackTrace();
//                }
//            }
//            if(httpClient != null){
//                try{
//                    httpClient.close();
//                }catch (IOException ioe){
//                    ioe.printStackTrace();
//                }
//            }
//        }
//        return ajaxResult;
//    }
    // 获取地图json
    public static String getEchartData(String url) {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 创建http请求
            URIBuilder builder = new URIBuilder(url);
            // builder.setParameters(params);
            HttpGet httpGet = new HttpGet(builder.build());
            response = httpClient.execute(httpGet);
            result = EntityUtils.toString(response.getEntity());
            // System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }

    public static String doPost(String url) {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try {
            URIBuilder builder = new URIBuilder(url);
            // 创建http请求
            HttpPost httpPost = new HttpPost(builder.build());
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }

    public static String doPost(String url, String jsonStr, String token) {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 创建http请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            if (Detect.notEmpty(token)) {
                httpPost.addHeader("token", token);
            }
            StringEntity entity = new StringEntity(jsonStr, "text/plain", "UTF-8");
            httpPost.setEntity(entity);
            // 设置超时时间
            RequestConfig requestConfig = RequestConfig
                    .custom()
                    .setConnectTimeout(3000)
                    .setConnectionRequestTimeout(1000)
                    .setSocketTimeout(3000)
                    .build();
            httpPost.setConfig(requestConfig);
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(), "utf-8");
            // System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }

    private static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};
        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String httpsDoGet(String url) throws Exception {
        // 构建请求参数
        String result = "";
        PrintWriter out = null;
        BufferedReader in = null;
        URL url2 = new URL(url);
        HttpsURLConnection urlCon = (HttpsURLConnection) url2.openConnection();
        try {
            urlCon.setHostnameVerifier(DO_NOT_VERIFY);
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setRequestMethod("GET");
            urlCon.setRequestProperty("Content-type", "application/json;charset=UTF-8");
            urlCon.setConnectTimeout(5 * 1000);// 设置超时时间
            urlCon.setReadTimeout(5 * 1000);
            // 发送请求参数
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
            // https(url,params);
            return null;
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            urlCon.disconnect();
        }
        return result;
    }

    public static BVideoToken doPostRefreshToken(String url) {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        BVideoToken videoToken = new BVideoToken();
        String result = "";
        try {
            URIBuilder builder = new URIBuilder(url);
            // 创建http请求
            HttpPost httpPost = new HttpPost(builder.build());
            httpPost.addHeader("Access-Control-Allow-Origin", "https://open.ys7.com");
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(), "utf-8");
            videoToken = JSON.parseObject(result, BVideoToken.class);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
        return videoToken;
    }

    public static void main(String[] args) throws Exception {
//        List<NameValuePair> params = new ArrayList<NameValuePair>();
//        String doGet = doGet("https://www.isqqw.com/asset/get/areas_v3/country/china.json", params, "admin", "public");
//        params.add(new BasicNameValuePair("Cookie", "JSESSIONID=0b124160-458b-4ed5-b665-2b988f120c14"));
//        params.add(new BasicNameValuePair("imageType", "button"));
//        params.add(new BasicNameValuePair("sortRule", "asc"));
//        String doPost=doPost("http://lfemcp.com/lfscada/designer/imgDatabase/query",params);
        Map<String, String> params = new HashMap<>();
        String https = httpsDoGet("https://www.isqqw.com/asset/get/areas_v3/country/china.json");
        System.out.println(https);
    }
}
